package com.software.servlet;

import com.software.model.Admin;
import com.software.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/adminLogin")
public class AdminLoginServlet extends HttpServlet {
    private AdminService adminService = new AdminService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用服务层的登录验证方法
        Admin admin = adminService.login(username, password);

        if (admin != null) {
            // 登录成功，设置session并跳转到商品管理页面
            HttpSession session = request.getSession();
            session.setAttribute("admin", admin); // 保存管理员信息
            response.sendRedirect("main.jsp");
        } else {
            // 登录失败，返回登录页面并提示错误信息
            request.setAttribute("errorMessage", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
